package com.java;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ClassNameKey
 * @Description
 * @Author liufei
 * @Date2021/9/6 11:04
 * @Version V1.0
 **/
@Configuration
public class KeyResolverConfiguration {
    /**
     * 编写基于请求路径的限流规则
     * 基于ip
     * 基于参数
     */
    //@Bean
    public KeyResolver pathKeyResolver(){
        //自定义的keyResolver
        return new KeyResolver() {
            @Override
            /**
             * ServerWebExchange
             * 上下文参数
             */
            public Mono<String> resolve(ServerWebExchange exchange) {

                return Mono.just(exchange.getRequest().getPath().toString());
            }
        };
    }

    /**
     * 编写基于请求参数的限流规则
     * 基于ip
     * 基于参数
     */
    @Bean
    public KeyResolver userKeyResolver(){
        return exchange -> Mono.just(
                exchange.getRequest().getQueryParams().getFirst("userId")
        );
    }
}
